package com.example.paperk.interceptor

import com.blankj.utilcode.util.LogUtils
import com.example.paperk.MD5Utils
import okhttp3.*
import okio.Buffer
import org.json.JSONObject

class SignInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var oldRequest: Request
        oldRequest = chain.request()
        var build = Request.Builder()
        build = Request.Builder()
        build.url(oldRequest.url())
        build.headers(oldRequest.headers())
        var oldBody: RequestBody
        oldBody = oldRequest.body()!!
        //获取requestbody中字符串
        var buffer: Buffer
        buffer = Buffer()
        var oldJson: String
        oldJson = ""
        oldBody.writeTo(buffer)
        val buff = ByteArray(1024)
        while (buffer.read(buff) != -1) {

            oldJson += String(buff)
        }
        buffer.clear()
        LogUtils.e("XRN", "oldJson:" + oldJson)
        oldJson = oldJson.substring(6, oldJson.lastIndexOf("}"))
        oldJson += "}"
        var values: String
        values = ""
        var json: String
        json = ""

        var job: JSONObject
        job = JSONObject(oldJson)
        job.keys()
        var it: Iterator<String>
        it = job.keys()
        while (it.hasNext()) {
            values = job.getString(it.next())
        }
        var sign: String
        sign = MD5Utils.createSign(values)
        job.put("sign", sign)
        json = job.toString()

        var body: RequestBody
        body = RequestBody.create(MediaType.parse("application/json"),json)
        build.post(body)
        return chain.proceed(build.build())
    }
}